package com.woniuxy.hotel.user.handler;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.woniuxy.hotel.exception.MyException;
import com.woniuxy.hotel.exception.MyExceptoinHandler;
import com.woniuxy.hotel.user.pojo.Customer;
import com.woniuxy.hotel.user.pojo.Vip;
import com.woniuxy.hotel.user.service.CustomerService;
import com.woniuxy.hotel.user.service.UserService;
import com.woniuxy.hotel.user.util.ExcelData;
import com.woniuxy.hotel.user.util.ExcelUtil;
import com.woniuxy.hotel.user.util.Page;
import com.woniuxy.hotel.user.util.RegexUtil;
import com.woniuxy.hotel.user.util.ResultDTO;

@Controller
@Scope("prototype")
@RequestMapping("/customer")
public class CustomerHandler extends MyExceptoinHandler{
	@Autowired
	private CustomerService customerService;
	@Autowired
	private UserService userService;

	@InitBinder("customer")
	public void init1(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("customer.");
	}

	@InitBinder("page")
	public void init2(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("page.");
	}

/*	*//**
	 * 通过身份证查询顾客信息
	 * 
	 * @return
	 *//*
	@RequestMapping("/findInfo")
	@ResponseBody
	public Customer findCustomerByIdentity(String identify) {
		Customer customer = customerService.findCustomerByIdentity(identify);
		return customer;
	}

	*//**
	 * 查询所有顾客信息，包括会员与非会员
	 * 
	 * @return
	 *//*
	@RequestMapping("/findAll")
	@ResponseBody
	public Collection<Customer> showAllCustomer() {
		return customerService.showAllCustomer();
	}

	*//**
	 * 查询所有会员信息
	 * 
	 * @return
	 *//*
	@RequestMapping("/findAllVip")
	@ResponseBody
	public Collection<Customer> showAllCustomerIsVip() {
		return customerService.showAllCustomerIsVip();
	}*/

	/**
	 * 查找登录用户的个人信息
	 * 
	 * @return
	 */
	@RequestMapping("/findLoginInfo")
	@ResponseBody
	public Customer findLoginInfo() {
		Subject subject = SecurityUtils.getSubject();
		String account = (String) subject.getPrincipal();
		if (account == null) {
			return null;
		}
		return customerService.findLoginInfo(account);
	}

	/**
	 * 根据宾客查询条件返回符合条件的宾客信息
	 * 
	 * @param customer
	 * @param page
	 * @return
	 */
	@RequestMapping("/findCustomer")
	@ResponseBody
	@RequiresRoles(value={"operator","superuser","admin"},logical = Logical.OR)
	public ResultDTO findCusomer(Customer customer, Page<Customer> page) {
		Page<Customer> customers = customerService.findCustomer(customer, page);
		return new ResultDTO(200, "宾客信息", customers);
	}
	/**
	 * 根据id查询宾客信息
	 * 
	 * @param customer
	 * @param page
	 * @return
	 */
	@RequestMapping("/findCustomerById")
	@ResponseBody
	@RequiresRoles(value={"operator","superuser","admin"},logical = Logical.OR)
	public ResultDTO findCusomerById(Integer id) {
		Customer customer=null;
		ResultDTO resultDTO=new ResultDTO();
		try{
			customer = customerService.findCustomerById(id);
			resultDTO.setCode(200);
			resultDTO.setObject(customer);
		}catch(RuntimeException e){
			resultDTO.setMassage(e.getMessage());
		}
		return resultDTO;
	}
	/**
	 * 更新手机号码
	 * @param CurrentPhone
	 * @param newPhone
	 * @return
	 */
	@RequestMapping(value="/updatePhone",method=RequestMethod.PUT)
	@ResponseBody
	@RequiresRoles(value={"operator","superuser","admin"},logical = Logical.OR)
	public ResultDTO updatePhone(String currentPhone,String newPhone){
		ResultDTO resultDTO=new ResultDTO();
		if(currentPhone.equals(newPhone)){
			resultDTO.setCode(400);
			resultDTO.setMassage("原号码与新号码相同");
			return resultDTO;
		}
		if(!RegexUtil.isMobile(newPhone)){
			resultDTO.setCode(400);
			resultDTO.setMassage("新手机号码格式有误");
			return resultDTO;
		}
		try{
			userService.updatePhone(currentPhone,newPhone);
			resultDTO.setCode(200);
			resultDTO.setMassage("success");
		}catch(RuntimeException e){
			resultDTO.setCode(400);
			resultDTO.setMassage(e.getMessage());
		}
		return resultDTO;
	}
	
	@RequestMapping(value="/exportExcel",method=RequestMethod.GET)
	@RequiresRoles(value={"operator","superuser","admin"},logical = Logical.OR)
	public void exportExcel(HttpServletResponse response){
		List<Customer> customers=customerService.showAllCustomer();
		List<String[]> data=new ArrayList<String[]>();
		for(Customer customer:customers){
			String[] arr=new String[12];
			arr[0]=customer.getId()+"";
			arr[1]=customer.getName()+"";
			arr[2]=customer.getCreateDate()+"";
			arr[3]=customer.getPic()+"";
			arr[4]=customer.getIdentify()+"";
			if(customer.getVip()!=null){
				arr[5]=customer.getVip().getVipId()+"";
				arr[6]=customer.getVip().getCreateDate()+"";
				arr[7]=customer.getVip().getDiscout()+"";
				arr[8]=customer.getVip().getPadmoney()+"";
				if(customer.getVip().getLevel()!=null){
					arr[9]=customer.getVip().getLevel().getName()+"";
					arr[10]=customer.getVip().getLevel().getRate()+"";
				}
			}
			if(customer.getUser()!=null){
				arr[11]=customer.getUser().getPhone()+"";
			}
			data.add(arr);
		}
		ExcelData excelData=new ExcelData();
		excelData.setData(data);
		excelData.setFileName("宾客信息.xls");
		String[] head={"id","姓名","创建日期","头像","身份证","会员编号","入会时间","折扣","消费金额","会员等级","会员折扣","手机号"};
		excelData.setHead(head);
		ExcelUtil.exportExcel(response, excelData);
	}
	@RequestMapping(value = "/importPM", method = RequestMethod.POST)
	@RequiresRoles(value={"superuser","admin"},logical = Logical.OR)
	public void importExcel(HttpServletRequest request,@RequestParam("file") MultipartFile file,HttpServletResponse response) throws MyException{
		 try {
	            List<Object[]> list = ExcelUtil.importExcel(file.getInputStream());
	            List<Vip> vips=new ArrayList<Vip>();
	            for(int i=0;i<list.size();i++){
	            	Vip vip=new Vip();
	            	vip.setVipId((String)list.get(i)[0]);
	            	vip.setPadmoney(new BigDecimal(list.get(i)[1].toString()));
	            	vips.add(vip);
	            }
	            List<String[]> resut=customerService.updateBatchPM(vips);
	            ExcelData excelData=new ExcelData();
	            String fileName=file.getOriginalFilename();
	    		excelData.setData(resut);
	    		excelData.setFileName(fileName);
	    		String[] head={"会员编号","消费金额","结果"};
	    		excelData.setHead(head);
	    		ExcelUtil.exportExcel(response, excelData);
	        } catch (Exception e) {
	            throw new MyException("文件解释失败");
	        }
	}
}
